import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import {
  Card,
  Form,
  Table,
  Divider,
  notification,
  Row,
  Col,
  Select,
  Button,
  Popover,
  Tag,
} from 'antd';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import { Link, routerRedux } from 'dva/router';
import MyTreeLineMarkTag from '../../components/_public/MyTreeLineMarkTag';
import { getParamUrl, getMathJax } from '../../utils/formatDataSource';
// import store from '../../index';
import Sticky from 'react-sticky-el';
import FreeScrollBar from 'react-free-scrollbar';
import MyStyle from '../index.less';

@connect(({ tag2, lesson2, loading }) => ({
  tag:tag2,
  lesson:lesson2,
  treeLoading: loading.effects['lesson2/kjConfig'],
}))
class MarkConfig extends PureComponent {
  state = {
    checked: false,
    wordDetail: this.props.tag.wordDetail,
    currentQuestion: {},
    currentIndex: null,
    questionType: null,
  };

  constructor(props) {
    super(props);
    this.submitMarkTag = this.submitMarkTag.bind(this);
    this.questionTagClose = this.questionTagClose.bind(this);
  }

  componentWillMount() {
    const { location: { search } } = this.props;
    const params = getParamUrl(search);
    this.setState({
      questionType: params.type,
    });
  }

  componentDidMount() {
    const { dispatch, location: { search } } = this.props;
    const params = getParamUrl(search);
    if (params.type == 1) {
      dispatch({
        type: 'tag/tagList',
      });
    }
    dispatch({
      type: 'tag/wordDetail',
      payload: params,
    }).then(() => {
      this.setState({
        wordDetail: this.props.tag.wordDetail,
      });
    });
    dispatch({
      type: 'lesson/kjConfig',
    });
  }

  handleChange = checked => {
    this.setState({ checked });
  };
  handleCategory = (item, type) => {
    const { currentQuestion, currentIndex, wordDetail } = this.state;
    if (!currentIndex && typeof currentIndex != 'undefined' && currentIndex != 0) {
      return;
    }
    switch (type) {
      case 0:
        currentQuestion.districtCategory = item;
        break;
      case 1:
        currentQuestion.yearCategory = item;
        break;
      case 2:
        currentQuestion.sourceCategory = item;
        break;
      case 3:
        currentQuestion.recommendCategory = item;
        break;
      case 4:
        currentQuestion.appearCategory = item;
        break;
      case 5:
        currentQuestion.wrongCategory = item;
        break;
      case 6:
        currentQuestion.tixingCategory = item;
        break;
      case 7:
        currentQuestion.nianjiCategory = item;
        break;
      case 8:
        currentQuestion.sfhjxCategory = item;
        break;
      case 9:
        currentQuestion.tihaoCategory = item;
        break;
      default:
        console.error('错误调用');
        break;
    }
    this.setState({
      currentQuestion,
    });
    const nextWordDetail = [...wordDetail];
    nextWordDetail.splice(currentIndex, 1, currentQuestion);
    this.setState({
      wordDetail: nextWordDetail,
    });
  };
  questionClick = (currentQuestion, currentIndex) => {
    this.setState({ currentQuestion, currentIndex });
  };

  questionTagClose(event, type, clickQuestion, clickIndex, typeItem) {
    event.preventDefault();
    const { wordDetail } = this.state;
    switch (type) {
      case 0:
        clickQuestion.districtCategory = null;
        break;
      case 1:
        clickQuestion.yearCategory = null;
        break;
      case 2:
        clickQuestion.sourceCategory = null;
        break;
      case 3:
        clickQuestion.recommendCategory = null;
        break;
      case 4:
        clickQuestion.appearCategory = null;
        break;
      case 5:
        clickQuestion.wrongCategory = null;
        break;

      case 6:
        clickQuestion.tixingCategory = null;
        break;
      case 7:
        clickQuestion.nianjiCategory = null;
        break;
      case 8:
        clickQuestion.sfhjxCategory = null;
        break;
      case 9:
        clickQuestion.tihaoCategory = null;
        break;

      case 10:
        const removeIndex = clickQuestion.questionTypeVoList.findIndex((value, index, arr) => {
          return typeItem.id == value.id;
        });
        const voIndex = clickQuestion.questionTypeVos.findIndex((value, index, arr) => {
          return typeItem.id == value.id;
        });
        clickQuestion.questionTypeVoList.splice(removeIndex, 1);
        clickQuestion.questionTypeVos.splice(voIndex, 1);
        break;
      default:
        console.error('错误调用');
        break;
    }
    const nextWordDetail = [...wordDetail];
    nextWordDetail.splice(clickIndex, 1, clickQuestion);
    this.setState({
      wordDetail: nextWordDetail,
    });
  }

  findTreeNode = (key, node, currentKey) => {
    var findNode = node.find(item => {
      return (item.id = key);
    });
    return findNode;
  };
  handleTreeClick = (item, selectedNode) => {
    const { location: { search } } = this.props;
    const { currentQuestion, currentIndex, wordDetail } = this.state;
    if (!currentIndex && typeof currentIndex != 'undefined' && currentIndex != 0) {
      return;
    }
    const params = getParamUrl(search);
    console.log(params);
    //普通题型
    if ((params.type == 1 && item.type == 5) || (params.type == 2 && item.type == 4)) {
      const questionType = {
        id: item.id,
        content: item.content,
        uniqueKey: item.uniqueKey,
      };
      currentQuestion.questionTypeVos = currentQuestion.questionTypeVos || [];
      currentQuestion.questionTypeVoList = currentQuestion.questionTypeVoList || [];
      //判断数组是否存在
      var haveRepeat = currentQuestion.questionTypeVos.find(value => {
        return value.uniqueKey == item.uniqueKey;
      });
      if (haveRepeat) {
        return;
      }
      var keyArrs = item.uniqueKey.split('_');

      let findResult = selectedNode;
      let questionList = {};
      let questionTypeVoList = [];
      keyArrs.map((k, i) => {
        // console.log(findResult)
        var node = {
          id: findResult.id,
          content: findResult.content,
        };
        questionTypeVoList.push(node);
        if (findResult.sons && findResult.sons.length > 0) {
          findResult = findResult.sons.find(son => son.id === Number(keyArrs[i + 1]));
        }
      });
      questionList.id = item.id;
      questionList.treeNodes = questionTypeVoList;
      currentQuestion.questionTypeVos.push(questionType);
      currentQuestion.questionTypeVoList.push(questionList);
      const nextWordDetail = [...wordDetail];
      nextWordDetail.splice(currentIndex, 1, currentQuestion);
      this.setState({
        wordDetail: nextWordDetail,
      });
    }
  };
  submitMarkTag = () => {
    const { wordDetail } = this.state;
    const { dispatch, location: { search } } = this.props;
    const params = getParamUrl(search);
    //检查所有题标签是否打上
    let errorCount = 0;
    let messageInfoArr = [];
    wordDetail.map((item, index) => {
      if (!item.districtCategory && params.type == 1) {
        messageInfoArr.push('第【' + (index + 1) + '】题的【地域】标签未打');
        errorCount++;
      }
      if (!item.yearCategory && params.type == 1) {
        messageInfoArr.push('第【' + (index + 1) + '】题的【年份】标签未打');
        errorCount++;
      }
      if (!item.sourceCategory && params.type == 1) {
        messageInfoArr.push('第【' + (index + 1) + '】题的【来源】标签未打');
        errorCount++;
      }
      if (!item.recommendCategory && params.type == 1) {
        messageInfoArr.push('第【' + (index + 1) + '】题的【推荐】标签未打');
        errorCount++;
      }
      if (!item.appearCategory && params.type == 1) {
        messageInfoArr.push('第【' + (index + 1) + '】题的【常考】标签未打');
        errorCount++;
      }
      if (!item.wrongCategory && params.type == 1) {
        messageInfoArr.push('第【' + (index + 1) + '】题的【易错】标签未打');
        errorCount++;
      }

      if (!item.tixingCategory && params.type == 1) {
        messageInfoArr.push('第【' + (index + 1) + '】题的【题型】标签未打');
        errorCount++;
      }
      if (!item.nianjiCategory && params.type == 1) {
        messageInfoArr.push('第【' + (index + 1) + '】题的【年级】标签未打');
        errorCount++;
      }
      if (!item.sfhjxCategory && params.type == 1) {
        messageInfoArr.push('第【' + (index + 1) + '】题的【是否含解析】标签未打');
        errorCount++;
      }
      if (!item.tihaoCategory && params.type == 1) {
        messageInfoArr.push('第【' + (index + 1) + '】题的【题号】标签未打');
        errorCount++;
      }

      if (!item.questionTypeVos || item.questionTypeVos.length <= 0) {
        if (params.type == 1) {
          messageInfoArr.push('第【' + (index + 1) + '】题的【知识树】标签未打');
        } else {
          messageInfoArr.push('第【' + (index + 1) + '】题的【知识树】标签未打');
        }
        errorCount++;
        // notification["info"]({
        //     message: '温馨提示',
        //     description: '第【'+(index+1)+'】题的【推荐】标签未打',
        // });
      }
    });
    if (errorCount) {
      notification['info']({
        message: '温馨提示',
        description: messageInfoArr.map((item, index) => {
          return <div key={index}>{item}</div>;
        }),
      });
      return;
    }
    //提交
    var wordMarkTag = {};
    wordMarkTag.type = params.type;
    wordMarkTag.wordId = params.wordId;
    wordMarkTag.wordMarkTagParamList = wordDetail;
    dispatch({
      type: 'tag/saveWordMark',
      payload: wordMarkTag,
    }).then(() => {
      dispatch(routerRedux.push('/parttime/mark'));
    });
  };
  getTagDivs = (data, tagIndex, item) => {
    if (!data) {
      return '';
    }
    return data.map((typeItem, index) => (
      <Popover
        key={index}
        overlayStyle={{ maxWidth: '400px' }}
        placement="right"
        trigger="hover"
        content={
          !typeItem.treeNodes
            ? ''
            : typeItem.treeNodes.map((item, i) => {
                return <span key={i}>{getMathJax(item.content)}</span>;
              })
        }
      >
        <Tag
          style={typeItem.id != null ? { display: 'inline-block' } : { display: 'none' }}
          closable
          onClose={e => {
            this.questionTagClose(e, 10, item, tagIndex, typeItem);
          }}
        >
          {!typeItem.treeNodes
            ? ''
            : typeItem.treeNodes.map((item, i) => {
                return (
                  <span key={i}>{getMathJax(item.content, 'afds', 50, MyStyle.mathPreview)}</span>
                );
              })}
        </Tag>
      </Popover>
    ));
  };

  render() {
    const { wordDetail, tagList } = this.props.tag;
    const { treeList } = this.props.lesson;
    const { CheckableTag } = Tag;
    const { currentQuestion, currentIndex } = this.state;
    const content = tagList.districtList.map((item, index) => {
      return (
        <div>
          <CheckableTag
            key={index}
            checked={currentQuestion.districtCategory == item}
            onChange={() => {
              this.handleCategory(item, 0);
            }}
          >
            {item}
          </CheckableTag>
          <br />
        </div>
      );
    });
    return (
      <PageHeaderLayout>
        <Card>
          <Row>
            <Col span={24} style={{ textAlign: 'right' }}>
              <Button
                type="primary"
                size="small"
                onClick={() => this.props.dispatch(routerRedux.push('/parttime/mark'))}
              >
                返回
              </Button>
            </Col>
          </Row>
        </Card>
        <Col span={12}>
          {wordDetail == null
            ? ''
            : wordDetail.map((item, i) => (
                <div
                  key={i}
                  style={{
                    borderColor: i == currentIndex ? 'red' : '',
                    borderStyle: i == currentIndex ? 'solid' : '',
                  }}
                >
                  <Card key={i} bordered={true} onClick={() => this.questionClick(item, i)}>
                    <div>{getMathJax(item.stem)}</div>
                    <div>{this.getTagDivs(item.questionTypeVoList, i, item)}</div>
                    <div>
                      <Tag
                        style={
                          item.districtCategory != null
                            ? { display: 'inline-block' }
                            : { display: 'none' }
                        }
                        closable
                        onClose={e => {
                          this.questionTagClose(e, 0, item, i);
                        }}
                      >
                        {item.districtCategory}
                      </Tag>
                      <Tag
                        style={
                          item.yearCategory != null
                            ? { display: 'inline-block' }
                            : { display: 'none' }
                        }
                        closable
                        onClose={e => {
                          this.questionTagClose(e, 1, item, i);
                        }}
                      >
                        {item.yearCategory}
                      </Tag>
                      <Tag
                        style={
                          item.sourceCategory != null
                            ? { display: 'inline-block' }
                            : { display: 'none' }
                        }
                        closable
                        onClose={e => {
                          this.questionTagClose(e, 2, item, i);
                        }}
                      >
                        {item.sourceCategory}
                      </Tag>
                      <Tag
                        style={
                          item.recommendCategory != null
                            ? { display: 'inline-block' }
                            : { display: 'none' }
                        }
                        closable
                        onClose={e => {
                          this.questionTagClose(e, 3, item, i);
                        }}
                      >
                        {item.recommendCategory}
                      </Tag>
                      <Tag
                        style={
                          item.appearCategory != null
                            ? { display: 'inline-block' }
                            : { display: 'none' }
                        }
                        closable
                        onClose={e => {
                          this.questionTagClose(e, 4, item, i);
                        }}
                      >
                        {item.appearCategory}
                      </Tag>
                      <Tag
                        style={
                          item.wrongCategory != null
                            ? { display: 'inline-block' }
                            : { display: 'none' }
                        }
                        closable
                        onClose={e => {
                          this.questionTagClose(e, 5, item, i);
                        }}
                      >
                        {item.wrongCategory}
                      </Tag>
                      <Tag
                        style={
                          item.tixingCategory != null
                            ? { display: 'inline-block' }
                            : { display: 'none' }
                        }
                        closable
                        onClose={e => {
                          this.questionTagClose(e, 6, item, i);
                        }}
                      >
                        {item.tixingCategory}
                      </Tag>
                      <Tag
                        style={
                          item.nianjiCategory != null
                            ? { display: 'inline-block' }
                            : { display: 'none' }
                        }
                        closable
                        onClose={e => {
                          this.questionTagClose(e, 7, item, i);
                        }}
                      >
                        {item.nianjiCategory}
                      </Tag>
                      <Tag
                        style={
                          item.sfhjxCategory != null
                            ? { display: 'inline-block' }
                            : { display: 'none' }
                        }
                        closable
                        onClose={e => {
                          this.questionTagClose(e, 8, item, i);
                        }}
                      >
                        {item.sfhjxCategory}
                      </Tag>
                      <Tag
                        style={
                          item.tihaoCategory != null
                            ? { display: 'inline-block' }
                            : { display: 'none' }
                        }
                        closable
                        onClose={e => {
                          this.questionTagClose(e, 9, item, i);
                        }}
                      >
                        {item.tihaoCategory}
                      </Tag>
                    </div>
                  </Card>
                </div>
              ))}
          <Card>
            <div hidden={wordDetail == null}>
              <Button type="primary" onClick={this.submitMarkTag}>
                提 交
              </Button>
            </div>
          </Card>
        </Col>
        <Col span={6}>
          <Sticky>
            <Card
              bordered={true}
              style={
                this.state.questionType == 1 ? { display: 'inline-block' } : { display: 'none' }
              }
            >
              <div>
                地区：<Popover placement="left" content={content}>
                  <Button type="primary" size="small">
                    选择区域
                  </Button>
                </Popover>
              </div>
              <div>
                年份:{' '}
                {tagList.yearCategoryList.map((item, i) => (
                  <CheckableTag
                    checked={currentQuestion.yearCategory == item}
                    onChange={() => {
                      this.handleCategory(item, 1);
                    }}
                    key={i}
                  >
                    {item}
                  </CheckableTag>
                ))}
              </div>
              <div>
                来源:{' '}
                {tagList.sourceCategoryList.map((item, i) => (
                  <CheckableTag
                    checked={currentQuestion.sourceCategory == item}
                    onChange={() => {
                      this.handleCategory(item, 2);
                    }}
                    key={i}
                  >
                    {item}
                  </CheckableTag>
                ))}
              </div>
              <div>
                是否推荐:{' '}
                {tagList.recommendCategoryList.map((item, i) => (
                  <CheckableTag
                    checked={currentQuestion.recommendCategory == item}
                    onChange={() => {
                      this.handleCategory(item, 3);
                    }}
                    key={i}
                  >
                    {item}
                  </CheckableTag>
                ))}
              </div>
              <div>
                常考:{' '}
                {tagList.appearCategoryList.map((item, i) => (
                  <CheckableTag
                    checked={currentQuestion.appearCategory == item}
                    onChange={() => {
                      this.handleCategory(item, 4);
                    }}
                    key={i}
                  >
                    {item}
                  </CheckableTag>
                ))}
              </div>
              <div>
                易错:{' '}
                {tagList.wrongCategoryList.map((item, i) => (
                  <CheckableTag
                    checked={currentQuestion.wrongCategory == item}
                    onChange={() => {
                      this.handleCategory(item, 5);
                    }}
                    key={i}
                  >
                    {item}
                  </CheckableTag>
                ))}
              </div>
              <div>
                题型:{' '}
                {tagList.tixingCategoryList.map((item, i) => (
                  <CheckableTag
                    checked={currentQuestion.tixingCategory == item}
                    onChange={() => {
                      this.handleCategory(item, 6);
                    }}
                    key={i}
                  >
                    {item}
                  </CheckableTag>
                ))}
              </div>
              <div>
                年级:{' '}
                {tagList.nianjiCategoryList.map((item, i) => (
                  <CheckableTag
                    checked={currentQuestion.nianjiCategory == item}
                    onChange={() => {
                      this.handleCategory(item, 7);
                    }}
                    key={i}
                  >
                    {item}
                  </CheckableTag>
                ))}
              </div>
              <div>
                是否含解析:{' '}
                {tagList.shifhanjiexiCategoryList.map((item, i) => (
                  <CheckableTag
                    checked={currentQuestion.sfhjxCategory == item}
                    onChange={() => {
                      this.handleCategory(item, 8);
                    }}
                    key={i}
                  >
                    {item}
                  </CheckableTag>
                ))}
              </div>
              <div>
                题号:{' '}
                {tagList.tihaoCategoryList.map((item, i) => (
                  <CheckableTag
                    checked={currentQuestion.tihaoCategory == item}
                    onChange={() => {
                      this.handleCategory(item, 9);
                    }}
                    key={i}
                  >
                    {item}
                  </CheckableTag>
                ))}
              </div>
            </Card>

          </Sticky>
        </Col>
        <Col span={6}>
          <Sticky>
            <Card>
              <div style={this.state.questionType == 1 ? { height: '600px' } : { height: '600px' }}>
                <FreeScrollBar>
                  <MyTreeLineMarkTag
                    dataSource={treeList}
                    handleTreeClick={this.handleTreeClick}
                    loading={this.props.treeLoading}
                  />
                </FreeScrollBar>
              </div>
            </Card>
          </Sticky>
        </Col>
      </PageHeaderLayout>
    );
  }
}

export default MarkConfig;
